// pages/bangdan/bangdan.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgwidth: wx.getSystemInfoSync().windowWidth,
    imgheight: wx.getSystemInfoSync().windowWidth * 0.4,

    xlb_key: 'QCIC82jD9e6JLK0OZcJW1mOB7C5v7QiR1537447029',
    mini_user_all: [],
    eventkey: '',
    userInfo: {},

    user_activity: {},
    supporters_head: [],
    activity: {},

    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    shareBoxShowStatus: 'none',

    endtime: {},

    friendShareStatus: "none",

    form_id_arr: [],

    activity_end_status: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let eventkey = options.eventkey;
    let _this = this;
    _this.setData({
      eventkey,
      mini_user_all: wx.getStorageSync('mini_user_all_' + eventkey) ? wx.getStorageSync('mini_user_all_' + eventkey).splice(0, 10) : [],
      activity: wx.getStorageSync('bangdan_activity_' + eventkey) ? wx.getStorageSync('bangdan_activity_' + eventkey) : {}
    })

    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              _this.dealUserInfo(res);
            }
          })
        }
      }
    })

    this.getAllUserList();
  },

  /**
   * 获取排行榜用户列表
   */
  getAllUserList: function () {
    let _this = this;
    wx.request({
      url: 'https://mini.xiaoliebian.com/api/mini/mini_count',
      data: {
        eventkey: _this.data.eventkey,
        xlb_key: _this.data.xlb_key
      },
      success(res) {
        res = res.data;
        if (parseInt(res.code) == 200) {
          let mini_user_all = res.mini_user_all;
          _this.setData({
            mini_user_all: mini_user_all
          })
          wx.setStorageSync('mini_user_all_' + _this.data.eventkey, mini_user_all)
        }
      }
    })
  },

  /**
   * 获取活动用户数据
   */
  getUserData: function () {
    let _this = this;
    let userInfo = _this.data.userInfo;
    let eventkey = _this.data.eventkey;
    let xlb_key = _this.data.xlb_key;

    wx.login({
      success(res) {
        let code = res.code;
        // 获取用户信息（创建用户）
        wx.request({
          url: 'https://mini.xiaoliebian.com/api/mini/mini_get_user_count',
          method: 'get',
          data: {
            eventkey,
            xlb_key,
            userInfo,
            code
          },
          success(res) {
            res = res.data;
            if (parseInt(res.code, 10) == 500) {
              wx.showToast({
                title: res.errmsg,
                icon: 'success',
                duration: 3000
              })
              _this.setData({
                use_able: false,
                errmsg: res.errmsg
              })
              return;
            }

            if (parseInt(res.activity.activity_end_type, 10) == 0) {
              let end = Date.parse(new Date(res.activity.activity_end_time)) || Date.parse(new Date(res.activity.activity_end_time.replace(/-/g, '/')));
              let intervalId = setInterval(function () {
                let now = Date.parse(new Date());
                let time_len = end - now;
                if (time_len < 0) {
                  wx.showToast({
                    title: "活动已经结束",
                    icon: 'success',
                    duration: 3000
                  })
                  clearInterval(intervalId);
                  return
                }
                let hour_timestamp = 3600;
                let minute_timestamp = 60;
                let hour = Math.floor(time_len / 1000 / hour_timestamp);
                let minute = Math.floor((time_len / 1000 - hour * hour_timestamp) / minute_timestamp);
                let second = Math.floor(time_len / 1000 - hour * hour_timestamp - minute * minute_timestamp)
                _this.setData({
                  endtime: {
                    hour,
                    minute,
                    second
                  }
                })
              }, 1000)
            }
            else {
              if (parseInt(res.activity.spread_end_award, 10) == 0) {
                wx.showToast({
                  title: "活动已经结束",
                  icon: 'success',
                  duration: 3000
                })
              }
            }

            let supporters_head = res.supporters_head;
            if (supporters_head.length < 24) {
              let len = 24 - supporters_head.length;
              for (let i = 0; i < len; i++) {
                supporters_head.push('https://mini.xiaoliebian.com/public/mini/public/icon/head.png');
              }
            }
            else {
              supporters_head = supporters_head.slice(0, 24);
            }

            _this.setData({
              user_activity: res,
              supporters_head: supporters_head,
              activity: res.activity,
              activity_end_status: res.activity.activity_end_type
            })

            wx.setStorageSync('bangdan_activity_' + _this.data.eventkey, res.activity)
          }
        })
      }
    })
  },

  /**
  * 处理用户授权登陆信息
  */
  dealUserInfo: function (res) {    
    this.setData({
      userInfo: res.userInfo
    })
    this.getUserData();
  },

  /**
   * 获取formID
   */
  submitInfo: function (e) {
    let form_id = e.detail.formId;
    let from_id_array = this.data.form_id_arr;
    from_id_array.push(form_id);
    this.setData({
      form_id_arr: from_id_array
    })
  },

  /**
   * 第一次授权登陆
   */
  bindGetUserInfo: function (e) {
    this.dealUserInfo(e.detail);
  },

  /**
   * 底部分享页面的显示隐藏控制
   */
  hideShareBox: function () {
    this.setData({
      shareBoxShowStatus: 'none'
    })
  },

  showShareBox: function () {
    this.setData({
      shareBoxShowStatus: 'block'
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.saveFormId();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.saveFormId();
  },

  onPullDownRefresh: function () {
    this.getAllUserList();
    this.getUserData();
    setTimeout(function () {
      wx.stopPullDownRefresh()
    }, 2000)
  },

  /**
   * 保存formID
   */
  saveFormId: function () {
    let _this = this;
    let form_id_array = this.data.form_id_arr;
    let xlb_key = this.data.xlb_key;
    let openid = this.data.user_activity.openid;
    let eventkey = this.data.eventkey;

    wx.request({
      url: 'https://mini.xiaoliebian.com/api/mini/mini_save_form_id',
      method: 'POST',
      data: {
        form_id_array,
        xlb_key,
        openid,
        eventkey
      },
      success(res) {
        if (parseInt(res.data.code, 10) == 200) {
          _this.setData({
            form_id_arr: []
          })
        }
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let _this = this;
    let group_share_text = _this.data.activity.group_share_text;
    group_share_text = group_share_text.replace(/\{nickname\}/g, _this.data.userInfo.nickName);
    return {
      title: group_share_text,
      path: 'pages/xlb_plug/plug?eventkey=' + _this.data.eventkey + '&serial_no=' + _this.data.user_activity.serial_no,
      imageUrl: _this.data.activity.group_litpic
    }
  },

  hideFriendShareBox: function () {
    this.setData({
      friendShareStatus: 'none'
    })
  },

  onShareQuanziMessage: function () {
    let _this = this;
    let eventkey = _this.data.eventkey;
    let xlb_key = _this.data.xlb_key;
    let serial_no = _this.data.user_activity.serial_no;

    wx.request({
      url: 'https://mini.xiaoliebian.com/api/mini/generate_share_image',
      method: 'POST',
      data: {
        eventkey,
        xlb_key,
        serial_no
      },
      success(res) {
        res = res.data;
        if (parseInt(res.code) == 200) {
          let url = "https://mini.xiaoliebian.com" + res.url;

          wx.downloadFile({
            url: url,
            success(res) {
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success() {
                  wx.hideLoading()
                  // wx.showModal({
                  //   title: '提示',
                  //   content: '图片已经保存到相册，快去分享吧！'
                  // })
                  _this.setData({
                    friendShareStatus: "block"
                  })
                },
                fail(res) {
                  console.log(res);
                }
              })
            },
            fail(res) {
              console.log(res);
            }
          })
          return;
        }

        wx.showToast({
          title: res.errmsg,
          icon: 'success',
          duration: 3000
        })
      }
    })
  },

  setClipboardData: function () {
    let _this = this;
    wx.setClipboardData({
      data: _this.data.activity.friends_share_text,
      success: function (res) {
        _this.setData({
          friendShareStatus: "none"
        })

        wx.showToast({
          title: "复制成功",
          icon: 'success',
          duration: 3000
        })
      }
    })
  }
})